const axios = require('axios');

// 测试API端点
const API_BASE_URL = 'http://localhost:3000/api/users';

// 测试微信登录后使用token访问受保护的接口
async function testWeChatAuthFlow() {
  try {
    // 测试数据
    const testData = {
      phone_number: '13800138002',
      openid: 'test_openid_auth_12345',
      unionid: 'test_unionid_auth_12345'
    };
    
    console.log('Testing WeChat authentication flow...');
    
    // 1. 微信手机号登录
    console.log('\n1. Logging in with WeChat phone number...');
    const loginResponse = await axios.post(`${API_BASE_URL}/wechat-phone-login`, testData);
    console.log('Login response:', loginResponse.data);
    
    const { token, user } = loginResponse.data;
    
    // 验证响应数据
    if (!token || !user) {
      throw new Error('Missing token or user in login response');
    }
    
    console.log(`User logged in with ID: ${user.id}`);
    
    // 2. 使用token访问受保护的接口
    console.log('\n2. Accessing protected user endpoint with token...');
    const protectedResponse = await axios.get(`${API_BASE_URL}/${user.id}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    console.log('Protected endpoint response:', protectedResponse.data);
    
    // 验证返回的用户数据
    if (protectedResponse.data.id !== user.id) {
      throw new Error('User ID mismatch in protected endpoint');
    }
    
    console.log('\n3. Accessing all users endpoint with token...');
    const allUsersResponse = await axios.get(`${API_BASE_URL}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    console.log(`Retrieved ${allUsersResponse.data.length} users`);
    
    // 验证返回的数据包含刚创建的用户
    const foundUser = allUsersResponse.data.find(u => u.id === user.id);
    if (!foundUser) {
      throw new Error('Created user not found in all users list');
    }
    
    console.log('\nAll authentication flow tests passed!');
    
  } catch (error) {
    console.error('Test failed:', error.response ? error.response.data : error.message);
  }
}

testWeChatAuthFlow();
